package api

import (
	"net/http"
	"strconv"

	"gitee.com/liumou_site/go-network-monitoring/service"
	"gitee.com/liumou_site/go-network-monitoring/types"
	"github.com/gin-gonic/gin"
)

// ProcessAPIHandler 进程监控API处理器
type ProcessAPIHandler struct {
	processService *service.ProcessMonitorService
}

// NewProcessAPIHandler 创建进程监控API处理器实例
func NewProcessAPIHandler() *ProcessAPIHandler {
	return &ProcessAPIHandler{
		processService: service.GetGlobalProcessMonitor(),
	}
}

// GetProcessConnectionsAPI 获取所有进程连接API
// GET /api/processes/connections
// 返回网络监听明细表数据切片
func (h *ProcessAPIHandler) GetProcessConnectionsAPI(c *gin.Context) {
	connections, err := h.processService.GetNetworkConnectionDetails()
	if err != nil {
		c.JSON(http.StatusInternalServerError, types.ProcessAPIResponse{
			Success: false,
			Error:   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, connections)
}

// GetProcessStatsAPI 获取指定进程统计API
// GET /api/processes/:pid
// 返回指定PID的进程网络活动统计
func (h *ProcessAPIHandler) GetProcessStatsAPI(c *gin.Context) {
	pidStr := c.Param("pid")
	pid, err := strconv.ParseInt(pidStr, 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, types.ProcessAPIResponse{
			Success: false,
			Error:   "无效的进程ID",
		})
		return
	}

	stats, err := h.processService.GetProcessStats(int32(pid))
	if err != nil {
		c.JSON(http.StatusInternalServerError, types.ProcessAPIResponse{
			Success: false,
			Error:   err.Error(),
		})
		return
	}

	if stats == nil {
		c.JSON(http.StatusNotFound, types.ProcessAPIResponse{
			Success: false,
			Error:   "进程未找到或无网络活动",
		})
		return
	}

	// 获取进程相关的连接信息
	connections, _ := h.processService.GetProcessConnections()
	processConnections := []types.ProcessConnection{}
	for _, conn := range connections {
		if conn.PID == int32(pid) {
			processConnections = append(processConnections, conn)
		}
	}

	// 构建详细响应 - 使用新的数据模型
	processDetail := types.NewProcessDetail(int32(pid))
	processDetail.ProcessName = stats.ProcessName
	processDetail.Executable = stats.Executable
	processDetail.Username = stats.Username
	processDetail.Status = "running"
	processDetail.IsAlive = stats.IsAlive
	processDetail.HasNetworkActivity = stats.TotalConnections > 0
	processDetail.NetworkConnections = stats.TotalConnections
	processDetail.TCPConnections = stats.ActiveTCP
	processDetail.UDPConnections = stats.ActiveUDP
	processDetail.ListeningPorts = len(stats.ListeningPorts)
	processDetail.TotalBytesSent = stats.TotalSent
	processDetail.TotalBytesRecv = stats.TotalRecv
	processDetail.CurrentSpeedUp = stats.SpeedUp
	processDetail.CurrentSpeedDown = stats.SpeedDown
	
	c.JSON(http.StatusOK, types.ProcessAPIResponse{
		Success: true,
		Data:    processDetail,
	})
}

// GetAllProcessStatsAPI 获取所有进程统计API
// GET /api/processes
// 返回进程明细表数据切片
func (h *ProcessAPIHandler) GetAllProcessStatsAPI(c *gin.Context) {
	processes, err := h.processService.GetProcessDetails()
	if err != nil {
		c.JSON(http.StatusInternalServerError, types.ProcessAPIResponse{
			Success: false,
			Error:   err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, processes)
}

// GetProcessSpeedStatsAPI 获取进程速度统计API
// GET /api/processes/speed
// 返回所有进程的实时速度统计
func (h *ProcessAPIHandler) GetProcessSpeedStatsAPI(c *gin.Context) {
	// 首先手动更新一次数据
	h.processService.Update()

	// 获取所有进程统计（包含速度数据）
	stats, err := h.processService.GetAllProcessStats()
	if err != nil {
		c.JSON(http.StatusInternalServerError, types.ProcessAPIResponse{
			Success: false,
			Error:   err.Error(),
		})
		return
	}

	// 只返回有速度数据的进程
	processesWithSpeed := []types.ProcessInfo{}
	for _, proc := range stats {
		if proc.SpeedUp > 0 || proc.SpeedDown > 0 || proc.TotalSent > 0 || proc.TotalRecv > 0 {
			processesWithSpeed = append(processesWithSpeed, proc)
		}
	}

	c.JSON(http.StatusOK, types.ProcessAPIResponse{
		Success: true,
		Data:    processesWithSpeed,
		Count:   len(processesWithSpeed),
	})
}

// GetProcessStatsSummaryAPI 获取进程统计汇总API
// GET /api/processes/stats
// 返回全局进程监控统计数据（直接返回数据结构）
func (h *ProcessAPIHandler) GetProcessStatsSummaryAPI(c *gin.Context) {
	stats, err := h.processService.GetAllProcessStats()
	if err != nil {
		c.JSON(http.StatusInternalServerError, types.ProcessAPIResponse{
			Success: false,
			Error:   err.Error(),
		})
		return
	}

	connections, err := h.processService.GetProcessConnections()
	if err != nil {
		c.JSON(http.StatusInternalServerError, types.ProcessAPIResponse{
			Success: false,
			Error:   err.Error(),
		})
		return
	}

	// 构建新的统计数据结构
	statsData := h.processService.BuildProcessMonitoringStats(stats, connections)
	c.JSON(http.StatusOK, statsData)
}
